package cn.kgc.javaweb.servlet;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import cn.kgc.javaweb.dto.PageDTO;
import cn.kgc.javaweb.entity.SysUser;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.UserServiceImpl;
import cn.kgc.javaweb.utils.LayUtil;
import cn.kgc.javaweb.utils.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/6/27
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    //生成验证码图片
    protected void captcha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LineCaptcha lineCaptcha = new LineCaptcha(260, 100, 4, 5);
        String code = lineCaptcha.getCode();
        //将验证码存入 session
        req.getSession().setAttribute("captcha", code);

        //将验证码图片响应给前端页面
        ServletOutputStream outputStream = resp.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();
    }

    //注册
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        //使用工具类 将密码加密
        sysUser.setPassword(SecureUtil.md5(password));

        Boolean b = userService.addUser(sysUser);
        HashMap<String, Object> map = new HashMap<>();
        if (b) {  //注册成功
            map.put("code", 0);
            map.put("msg", "注册成功");
        } else {//注册失败
            map.put("code", 500);
            map.put("msg", "注册失败");
        }

        //将map集合响应给前端页面
        ResponseUtil.write(resp, map);

    }

    // 登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        SysUser sysUser = new SysUser();
        sysUser.setPassword(SecureUtil.md5(password));
        sysUser.setUsername(username);

        //判定用户的验证码是否正确
        String captcha = (String) req.getSession().getAttribute("captcha");
        if (captcha.equals(code)) {  //用户登录
            Map<String, Object> map = userService.login(sysUser);
            //将用户信息 放入session 用于权限的判定
            req.getSession().setAttribute("user", map.get("user"));
            ResponseUtil.write(resp, map);
        } else {  //提示用户验证码不正确

            HashMap<String, Object> map = new HashMap<>();
            map.put("code", "500");
            map.put("msg", "验证码不正确!");
            ResponseUtil.write(resp, map);
        }


    }

    // 查询所有用户信息
    protected void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取请求参数  兼容搜索功能

        String username = req.getParameter("username");
        //获取分页相关参数
        Integer page = Integer.parseInt(req.getParameter("page"));
        Integer limit = Integer.parseInt(req.getParameter("limit"));

        PageDTO pageDTO = new PageDTO(username, page, limit);


        LayUtil layUtil = userService.selectAll(pageDTO);
        //layUtil  -> json 格式
        ResponseUtil.write(resp, layUtil);

    }


    // 更新用户信息
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户更新信息  id username nickName sex  phone  roleId
        Integer id = Integer.parseInt(req.getParameter("id"));
        String nickName = req.getParameter("nickName");
        Integer sex = Integer.parseInt(req.getParameter("sex"));
        String phone = req.getParameter("phone");
        Integer roleId = Integer.parseInt(req.getParameter("roleId"));

        SysUser user = SysUser.builder().id(id).nickName(nickName).phone(phone).sex(sex).roleId(roleId).build();

        Map<String, Object> map = userService.updateUser(user);

        ResponseUtil.write(resp, map);

    }


    // 添加用户信息
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取用户添加信息   username nickName sex  phone  roleId
        String username = req.getParameter("username");
        String nickName = req.getParameter("nickName");
        Integer sex = Integer.parseInt(req.getParameter("sex"));
        String phone = req.getParameter("phone");
        Integer roleId = Integer.parseInt(req.getParameter("roleId"));

        SysUser user = SysUser.builder().username(username).password(SecureUtil.md5("12345")).nickName(nickName).phone(phone).sex(sex).roleId(roleId).build();

        Map<String, Object> map = userService.addUserInfo(user);
        ResponseUtil.write(resp, map);


    }


    // 删除用户信息
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 删除单个数据 和批量删除使用相同的 key
        // 删除一条数据  传递的值是一个id    批量删除  传递的id 是一个使用逗号分割的字符串  1,2,3
        String ids = req.getParameter("ids");
        Map<String, Object> map = userService.deleteByIds(ids);
        ResponseUtil.write(resp, map);
    }


    // 修改用户状态
    protected void state(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.parseInt(req.getParameter("id"));
        Integer state = Integer.parseInt(req.getParameter("state"));

        Map<String, Object> map = userService.updateState(id, state);

        ResponseUtil.write(resp, map);

    }

    // 重置密码
    protected void replacepwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取session 从session中获取用户相关信息
        SysUser user = (SysUser) req.getSession().getAttribute("user");
        //获取前端传递的新旧密码

        String oldpwd = req.getParameter("oldpwd");
        String newpwd = req.getParameter("newpwd");
        String id = req.getParameter("id");

       if(id==null){ //修改密码
           //比较oldpwd 和 session 中获取的密码
           if (user.getPassword().equals(SecureUtil.md5(oldpwd))) {
               Integer intId = user.getId();
               Map<String, Object> map = userService.replacepwd(intId, SecureUtil.md5(newpwd));
               ResponseUtil.write(resp, map);
           } else {
               HashMap<String, Object> map = new HashMap<>();
               map.put("code", "500");
               map.put("msg", "请输入正确的原始密码");
               ResponseUtil.write(resp, map);
           }

       }else{ //重置密码
           String pwd = SecureUtil.md5("12345");
           Integer intId = Integer.parseInt(id) ;
           Map<String, Object> map = userService.replacepwd(intId, pwd);
           ResponseUtil.write(resp, map);
       }
    }

    // 退出登录
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getSession().invalidate();

        HashMap<String, Object> map = new HashMap<>();

        map.put("code", 0);
        map.put("msg", "退出登录成功");

        ResponseUtil.write(resp, map);

    }

}
